<template>
  <div class="app-container home">
    <div id="mapDiv">
      <div class="dd-legend">
        <el-checkbox
          @change="changeVisible('yuanluo',$event)"
          checked
        >院落</el-checkbox>
        <ul>
          <li>已签约<span style="background-color:green"></span></li>
          <li>未签约<span style="background-color:red"></span></li>
        </ul>
        <el-checkbox
          @change="changeVisible('zhuang',$event)"
          checked
        >幢</el-checkbox>
        <ul>
          <li>已签约<span style="background-color:green"></span></li>
          <li>未签约<span style="background-color:red"></span></li>
        </ul>
      </div>
      <div class="dd-chart-container">
        <span class="title">当前申请数量</span>
        <span class="value">{{staticsData.todaySqsl}}</span>
        <span class="title">当前签约率</span>
        <span class="value">{{staticsData.qyl}}%</span>
        <span class="title">今日采集数量</span>
        <span class="value">户数：{{staticsData.todayCjsl}}</span>
        <span class="title">今日完成评估</span>
        <span class="value">户数：{{staticsData.todayPgsl}}</span>
        <!-- <span class="title">今日完成签约</span>
        <span class="value">户数：{{staticsData.todayQysl}}</span> -->
        <!-- <span class="value">院落：{{staticsData.todayYlqysl}}</span> -->
        <span class="title">近7日采集数量</span>
        <div
          class="dd-inner-chart"
          ref="cjslChart"
        ></div>
        <span class="title">近7日签约趋势</span>
        <div
          class="dd-inner-chart"
          ref="qyqsChart"
        ></div>
      </div>
      <div
        class="dd-chart-container"
        style="right:420px;bottom:10px;height:335px;top:auto;padding-bottom:35px;"
      >
        <span class="title">各标段统计情况</span>
        <div
          class="dd-inner-chart"
          style="height:85%"
          ref="bdslChart"
        ></div>
        <el-row style="position:absolute;bottom:5px;left:0px;width:100%;height:35px;">
          <el-col :span="2">
            全选<br>
            <el-checkbox
              :indeterminate="isIndeterminate"
              v-model="checkAll"
              @change="handleCheckAllChange"
            ></el-checkbox>
          </el-col>
          <el-col
            :span="3"
            :offset="1"
          >
            标段1<br>
            <el-checkbox
              key="标段1"
              v-model="checkedCities[0]"
              @change="handleCheckChange($event,'标段1')"
            ></el-checkbox>
          </el-col>
          <el-col
            :span="4"
            :offset="2"
          >
            标段2<br>
            <el-checkbox
              key="标段2"
              v-model="checkedCities[1]"
              @change="handleCheckChange($event,'标段2')"
            ></el-checkbox>
          </el-col>
          <el-col
            :span="3"
            :offset="2"
          >
            标段3<br>
            <el-checkbox
              key="标段3"
              v-model="checkedCities[2]"
              @change="handleCheckChange($event,'标段3')"
            ></el-checkbox>
          </el-col>
          <el-col
            :span="3"
            :offset="2"
          >
            标段4<br>
            <el-checkbox
              v-model="checkedCities[3]"
              key="标段4"
              @change="handleCheckChange($event,'标段4')"
            ></el-checkbox>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import "ol/ol.css";
import { Map, View } from "ol";
import TileLayer from 'ol/layer/Tile';
import Projection from 'ol/proj/Projection';
import * as olControl from 'ol/control';
import proj4 from 'proj4';
import { register } from 'ol/proj/proj4';
import TileGrid from 'ol/tilegrid/TileGrid';
import XYZ from 'ol/source/XYZ';
import GeoJSON from 'ol/format/GeoJSON';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import { Stroke, Style, Fill } from 'ol/style';
import { fromLonLat, toLonLat } from 'ol/proj';
import epsg9900 from '../utils/epsgParams';

import * as echarts from 'echarts';

import { yuanluoLayer } from '@/api/business/layer';
import { getHomeStaticsInfo } from "@/api/business/hu_info";


export default {
  name: "Index",
  data() {
    return {
      map: {},
      mapView: {},
      staticsData: {},
      checkAll: true,
      checkedCities: [true, true, true, true],
      isIndeterminate: false,
      bdslChartData: []
    };
  },
  computed: {
    opened() {
      return this.$store.state.app.sidebar.opened
    }
  },
  watch: {
    opened() {
      this.updateMapView();
    }
  },
  methods: {
    initMap() {
      proj4.defs('EPSG:990000', epsg9900.define);
      register(proj4);
      const projection = new Projection({
        code: "EPSG:990000",
        units: epsg9900.units,
        extent: epsg9900.extent
      });

      const tileSource = new XYZ({
        maxZoom: 8,
        minZoom: 0,
        projection: projection,
        transition: 0,
        tileGrid: new TileGrid({
          tileSize: 256,
          origin: epsg9900.origin,
          extent: epsg9900.extent,
          resolutions: epsg9900.tile_resolutions
        }),
        tileUrlFunction: (tileCoord) => {
          const z = "L" + this.zeroPad(tileCoord[0], 2, 10);
          const x = "C" + this.zeroPad(tileCoord[1], 8, 16);
          const y = "R" + this.zeroPad(tileCoord[2], 8, 16);
          return `${process.env.VUE_APP_BASEMAP}/Layers/_alllayers/${z}/${y}/${x}.png`;
        }
      })
      const baseLayer = new TileLayer({
        id: "base_layer_0",
        source: tileSource,
        wrapX: true
      });

      this.map = new Map({
        target: 'mapDiv',
        layers: [baseLayer],
        controls: olControl.defaults({
          zoom: false
        }),
        view: new View({
          projection: projection,
          center: epsg9900.center,
          zoom: 6,
          minZoom: 0,
          maxZoom: 12
        })
      });

      this.map.on("singleclick", (e) => {
        console.log(e);
      })

    },
    zeroPad(num, len, radix) {
      let str = num.toString(radix || 10);
      while (str.length < len) {
        str = "0" + str;
      }
      return str;
    },
    addGeoJsonLayer(layerId, data) {
      const vectorLayer = new VectorLayer({
        id: layerId,
        source: new VectorSource({
          features: new GeoJSON().readFeatures(data)
        }),
        style: this.graphicStyleFunction,
      });

      this.map.addLayer(vectorLayer);
    },
    graphicStyleFunction(feature) {
      if (feature.get("isSign") == "1") {
        return new Style({
          stroke: new Stroke({
            color: 'rgba(0, 0, 255, 0.4)',
            lineDash: [4],
            width: 4,
          }),
          fill: new Fill({
            color: 'green',
          }),
        })
      } else {
        return new Style({
          stroke: new Stroke({
            color: 'rgba(0, 0, 255, 0.4)',
            lineDash: [4],
            width: 4,
          }),
          fill: new Fill({
            color: 'red',
          }),
        })
      }
    },
    addBusLayer(layerId) {
      yuanluoLayer({ "layerId": layerId }).then(res => {
        this.addGeoJsonLayer(layerId, res.data);
      })
    },
    getLayerById(id) {
      for (let l of this.map.getLayers().getArray()) {
        if (l.get("id") == id) {
          return l;
        }
      }
      return undefined;
    },
    changeVisible(layerId, visible) {
      const layer = this.getLayerById(layerId);
      if (layer) {
        layer.setVisible(visible)
        if (visible) {
          yuanluoLayer({ "layerId": layerId }).then(res => {
            layer.source.features = res.data;
          })
        }
      }
    },
    updateMapView() {
      setTimeout(() => {
        if (this.map) {
          this.map.updateSize();
        }
      }, 300);
    },
    initQysqChart(data) {
      // const data = [
      //   { name: "11-16", value: 5 },
      //   { name: "11-17", value: 10 },
      //   { name: "11-18", value: 7 },
      //   { name: "11-19", value: 12 },
      //   { name: "11-20", value: 0 },
      //   { name: "11-21", value: 0 },
      //   { name: "11-22", value: 14 },
      // ];
      const myChart = echarts.init(this.$refs.qyqsChart);
      const option = {
        tooltip: {
          trigger: 'axis',
        },
        grid: {
          top: '6%',
          right: '3%',
          bottom: '3%',
          left: '0%',
          containLabel: true,
          show: true,
          borderColor: 'rgba(0, 240, 255, 0.3)'
        },
        xAxis: [{
          type: 'category',
          data: data.map(d => d.name),
          axisTick: {
            alignWithLabel: true,
            show: false
          },
          axisLabel: {
            color: '#FFF'
          }
        }],
        yAxis: [{
          type: 'value',
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#FFF'
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(0, 240, 255, 0.3)'
            }
          }
        }],
        series: [{
          name: '签约趋势',
          type: 'line',
          data: data,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
              offset: 0,
              color: 'red'
            }, {
              offset: 1,
              color: 'blue'
            }])
          }
        }]
      };
      myChart.setOption(option);
      window.addEventListener('resize', () => { myChart.resize() });
    },
    initCjslChart(data) {
      // const data = [
      //   { name: "11-16", value: 33 },
      //   { name: "11-17", value: 23 },
      //   { name: "11-18", value: 39 },
      //   { name: "11-19", value: 40 },
      //   { name: "11-20", value: 0 },
      //   { name: "11-21", value: 0 },
      //   { name: "11-22", value: 48 },
      // ];
      const myChart = echarts.init(this.$refs.cjslChart);
      const option = {
        tooltip: {
          trigger: 'item',
          axisPointer: {
            type: 'line'
          }
        },
        grid: {
          top: '6%',
          right: '3%',
          bottom: '3%',
          left: '0%',
          containLabel: true,
          show: true,
          borderColor: 'rgba(0, 240, 255, 0.3)'
        },
        xAxis: [{
          type: 'category',
          data: data.map(d => d.name),
          axisTick: {
            alignWithLabel: true,
            show: false
          },
          axisLabel: {
            color: '#FFF'
          }
        }],
        yAxis: [{
          type: 'value',
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#FFF'
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(0, 240, 255, 0.3)'
            }
          }
        }],
        series: [{
          name: '采集数量',
          type: 'bar',
          barWidth: '10',
          data: data,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
              offset: 0,
              color: 'red'
            }, {
              offset: 1,
              color: 'blue'
            }])
          }
        }]
      };
      myChart.setOption(option);
      window.addEventListener('resize', () => { myChart.resize() });
    },
    initBdslChart(data, isAllData = true) {
      if (isAllData) {
        this.bdslChartData = data
      }
      const xAxisData = data.map(element => element.org_name)
      const gtslData = data.map(element => element.gtsl)
      const sqslData = data.map(element => element.sqsl)
      const xfslData = data.map(element => element.xfsl)
      const qyslData = data.map(element => element.qysl)
      const myChart = echarts.init(this.$refs.bdslChart);
      const option = {
        color: ["#5470c6", "#91cc75", "#fac858", "#ee6666", "#73c0de", "#3ba272", "#fc8452", "#9a60b4", "#ea7ccc"],
        tooltip: {
          trigger: 'item',
        },
        grid: {
          top: '10%',
          right: '3%',
          bottom: '3%',
          left: '0%',
          containLabel: true,
          show: true,
          borderColor: 'rgba(0, 240, 255, 0.3)'
        },
        xAxis: [{
          type: 'category',
          data: xAxisData,
          axisTick: {
            alignWithLabel: true,
            show: false
          },
          axisLabel: {
            color: '#FFF',
            show: false
          }
        }],
        legend: {
          data: ["沟通数量", "申请数量", "选房数量", "签约数量"],
          textStyle: {
            color: "#fff"
          }
        },
        yAxis: [{
          type: 'value',
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#FFF'
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(0, 240, 255, 0.3)'
            }
          }
        }],
        series: [{
          name: '沟通数量',
          type: 'bar',
          barWidth: '8',
          data: gtslData,
        }, {
          name: '申请数量',
          type: 'bar',
          barWidth: '8',
          data: sqslData,
        }, {
          name: '选房数量',
          type: 'bar',
          barWidth: '8',
          data: xfslData,
        }, {
          name: '签约数量',
          type: 'bar',
          barWidth: '8',
          data: qyslData,
        }]
      };
      myChart.setOption(option);
      window.addEventListener('resize', () => { myChart.resize() });
    },
    handleCheckAllChange(val) {
      if (val) {
        this.checkedCities = [true, true, true, true]
      } else {
        this.checkedCities = [false, false, false, false]
      }
      const chartData = this.bdslChartData.map((ele, idx) => {
        if (!this.checkedCities[idx]) {
          return {
            gtsl: 0,
            sqsl: 0,
            xfsl: 0,
            qysl: 0,
            org_name: ele.org_name
          }
        }
        return ele
      })
      this.initBdslChart(chartData, false)
      this.isIndeterminate = false;
    },
    handleCheckChange(val, tag) {
      const chartData = this.bdslChartData.map((ele, idx) => {
        if (!this.checkedCities[idx]) {
          return {
            gtsl: 0,
            sqsl: 0,
            xfsl: 0,
            qysl: 0,
            org_name: ele.org_name
          }
        }
        return ele
      })
      this.initBdslChart(chartData, false)
      const checkeds = this.checkedCities.filter(checked => checked)
      this.checkAll = checkeds.length == 4;
      this.isIndeterminate = checkeds.length > 0 && checkeds.length < 4;
    }
  },
  mounted() {
    this.initMap();
    this.addBusLayer("yuanluo");
    this.addBusLayer("zhuang");

    getHomeStaticsInfo().then(res => {
      this.staticsData = res.data;

      this.initCjslChart(this.staticsData.near7DaysCjsl);
      this.initQysqChart(this.staticsData.near7DaysQysl);
      this.initBdslChart(res.data.bdsl)
    })
  },
};
</script>

<style scoped lang="scss">
.home {
  height: calc(100vh - 50px);
  padding: 0px !important;
  #mapDiv {
    width: 100%;
    height: 100%;
  }

  .dd-chart-container,
  .dd-legend {
    position: absolute;
    z-index: 1000;
    top: 10px;
    left: 10px;
    // border-radius: 5px;
    border: dashed thin #ccc;
    background-color: rgba($color: #09374e, $alpha: 0.8);
    padding: 10px;
    & > * {
      color: #fff;
    }
    color: #fff;
  }

  .dd-chart-container {
    right: 10px;
    left: auto !important;
    width: 400px;
    bottom: 10px;
    text-align: center;
    overflow-y: auto;
    .title,
    .value {
      font-size: 16px;
      display: block;
      font-weight: bold;
      margin-bottom: 10px;
    }
    .value {
      color: #ecfd00 !important;
    }
    .dd-inner-chart {
      width: 100%;
      height: 32%;
    }
  }

  ul {
    padding: 5px 5px 5px 30px;
    margin: 0;
    list-style: none;
    & li {
      margin-top: 5px;
      line-height: 20px;
      span {
        display: inline-block;
        width: 15px;
        height: 15px;
        vertical-align: middle;
        margin-left: 10px;
        border: dashed thin rgba(0, 0, 255, 0.4);
      }
    }
  }

  font-family: "open sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 13px;
  color: #676a6c;
  overflow-x: hidden;
}
</style>

